package com.mzba.easy.weibo.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ZoomControls;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.widget.ImageZoomView;
import com.mzba.easy.weibo.widget.SimpleZoomListener;
import com.mzba.easy.weibo.widget.ZoomState;
/**
 * 查看图片 双手触摸放大缩小，单手拖放
 * @author 06peng
 *
 */
public class PhotoDetailActivity extends BasicActivity {

	private String mPicPath = null;
	private Bitmap bmp;  
	private byte[] tempBytes;
	private Bitmap tempBmp;

	private ImageZoomView mZoomView;
	private ZoomState mZoomState;
	private SimpleZoomListener mZoomListener;
	
	private final static int download_pic = 1;
	private ActionBar actionBar;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showimageview);
		
		actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.top_bg));
		actionBar.setTitle("查看大图");
		Intent intent = getIntent();
		mPicPath = intent.getStringExtra("pic_big");
		tempBytes = intent.getByteArrayExtra("thumbnail");
		
		mZoomView = (ImageZoomView)this.findViewById(R.id.zoomView);
		if (tempBytes != null) {
			tempBmp = ServiceUtils.bytesToBitmap(tempBytes);
		} else {
			tempBmp = ServiceUtils.drawableToBitmap(getResources().getDrawable(R.drawable.album_nophoto));
		}
		if (tempBmp != null) {
			mZoomView.setImageBitmap(tempBmp);
			mZoomView.invalidateImage();
		}
		if (mPicPath != null) {
			DownloadImgTask task = new DownloadImgTask();
			task.execute(mPicPath);
			mZoomView.setPorterDuffMode(true);
			mZoomView.setLoading(true);
			mZoomView.setProgress(0);
			mZoomView.invalidate();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, download_pic, 0, "下载").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
		} else if (item.getItemId() == download_pic) {
			UICore.eventTask(this, this, download_pic, "", null);
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case download_pic:
			downloadImage();
			break;
		default:
			break;
		}
	}
	
	private void downloadImage() {
		ServiceUtils.downLoadImage(mPicPath, AppContext.DOWNLOAD_PATH, null);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bmp != null)
			bmp.recycle();
		 mZoomView.setOnTouchListener(null);
		 if (mZoomState != null) {
			 mZoomState.deleteObservers();
		 }
	}
	
	private void resetZoomState() {
		mZoomState.setPanX(0.5f);
		mZoomState.setPanY(0.5f);
		mZoomState.setZoom(1f);
		mZoomState.notifyObservers();
	}

	public class DownloadImgTask extends AsyncTask<String, Float, Bitmap> {
		private static final String TAG = "DownloadImgTask";

		/** 下载准备工作。在UI线程中调用。 */
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");
		}

		/** 执行下载。在背景线程调用。 */
		protected Bitmap doInBackground(String... params) {
			Log.i(TAG, "doInBackground:" + params[0]);
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);
			InputStream is = null;
			ByteArrayOutputStream baos = null;
			try {
				HttpResponse httpResponse = httpClient.execute(httpGet);
				printHttpResponse(httpResponse);
				HttpEntity httpEntity = httpResponse.getEntity();
				long length = httpEntity.getContentLength();
				Log.i(TAG, "content length=" + length);
				is = httpEntity.getContent();
				if (is != null) {
					baos = new ByteArrayOutputStream();
					byte[] buf = new byte[128];
					int read = -1;
					int count = 0;
					while ((read = is.read(buf)) != -1) {
						baos.write(buf, 0, read);
						count += read;
						publishProgress(count * 1.0f / length);
					}
					Log.i(TAG, "count=" + count + " length=" + length);
					byte[] data = baos.toByteArray();
					Bitmap bit = BitmapFactory.decodeByteArray(data, 0, data.length);
					return bit;
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (baos != null) {
						baos.close();
					}
					if (is != null) {
						is.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		/** 更新下载进度。在UI线程调用。onProgressUpdate */
		protected void onProgressUpdate(Float... progress) {
			// LogOut.out(this, "onProgressUpdate");
			mZoomView.setProgress(progress[0]);
		}

		/** 通知下载任务完成。在UI线程调用。 */
		protected void onPostExecute(Bitmap bit) {
			Log.i(TAG, "onPostExecute");
			mZoomView.setPorterDuffMode(false);
			mZoomView.setLoading(false);
			mZoomView.setImageBitmap(bit);
			mZoomView.setImage(bit);
			mZoomState = new ZoomState();
			mZoomView.setZoomState(mZoomState);
			mZoomListener = new SimpleZoomListener();
			mZoomListener.setZoomState(mZoomState);
			mZoomView.setOnTouchListener(mZoomListener);
			ZoomControls zoomCtrl = (ZoomControls) findViewById(R.id.zoomCtrl);
			zoomCtrl.setOnZoomInClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					float z = mZoomState.getZoom() + 0.25f;
					mZoomState.setZoom(z);
					mZoomState.notifyObservers();
				}
			});
			zoomCtrl.setOnZoomOutClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					float z = mZoomState.getZoom() - 0.25f;
					mZoomState.setZoom(z);
					mZoomState.notifyObservers();
				}
			});
			resetZoomState();
		}

		protected void onCancelled() {
			Log.i(TAG, "DownloadImgTask cancel...");
			super.onCancelled();
		}

		private void printHttpResponse(HttpResponse httpResponse) {
			Header[] headerArr = httpResponse.getAllHeaders();
			for (int i = 0; i < headerArr.length; i++) {
				Header header = headerArr[i];
				Log.i(TAG, "name[" + header.getName() + "]value[" + header.getValue() + "]");
			}
			HttpParams params = httpResponse.getParams();
			Log.i(TAG, String.valueOf(params));
			Log.i(TAG, String.valueOf(httpResponse.getLocale()));
		}
	}

}
